<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
	* list users 
	* grant privileage user
	* edit, delete user
**/

class User extends CI_Controller {

	var $debug = '';
	var $per_page = '';

	public function __construct()
	{
		parent::__construct();	

		$logged_in = $this->session->userdata('logged_in');
		if($logged_in)
		{
		   $session_data = $this->session->userdata('logged_in');
		   $data['username'] = $session_data['username'];		   
		}
		else
		{
	     //If no session, redirect to login page
	     redirect('login', 'refresh');
   		}

		// gán giá trị tiêu đề form
		$this->template->set('nav',$this->uri->segment(1));
		$this->template->set('title', 'Người dùng');
		$this->template->set('section', 'Danh sách người dùng');

		$this->load->model('User_model');
		$this->load->model('Product_model');
		$this->load->model('User_revenue_model');
	}

	public function index()
	{
		// if search is not empty
		$search = $this->input->post('search');
		$user_cat = $this->input->post('user_cat');
		$cond_search = array();
		if(!empty($search))		
		{
			$data['search']	= $search;
			$cond_search['username'] = $search;
		}
		if(!empty($user_cat))
		{
			$data['user_cat'] = $user_cat;
			$cond_search['user_cat'] = $user_cat;
		}

		// retrieve list of users
		$users = $this->User_model->listUsers($cond_search);		

		$warning = $this->session->userdata('warning');
		if(!empty($warning))
		{
			$data['warning'] = $warning;
			$this->session->unset_userdata('warning');
		}

		// will be removed when feature live
		$data['notify'] = 'Hệ thống phân quyền đang được hoàn thiện';				

		$notify = $this->session->userdata('notify');
		if(!empty($notify))
		{
			$data['notify'] = $notify;
			$this->session->unset_userdata('notify');
		}

		if(!empty($users))
		{
			$data['users'] = $users;
		}
		else
		{			
			$data['notify'] = 'Chưa có dữ liệu người dùng ! Tạo người dùng ngay';
		}		

		$this->template->load('admin/template','admin/users',$data);
	}

	public function newUser()
	{
		$createBtn = $this->input->post('createBtn');		

		if(isset($createBtn))
		{			
			// validate input
			// username, password is generate, is_edit, is_view
			$this->load->library('form_validation');

			$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');			
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');

			if ($this->form_validation->run() == FALSE)
			{
				$data['error'] = validation_errors();
				$this->session->set_userdata('warning', $data['error']);				
			}
			else
			{
				//generate password
				$password = $this->util->generatePassword(8);
				$tmp_password = $password;
				$password = md5($password);

				// insert user
				$user = array(
						'username'	=>	$this->input->post('username'),
						'fullname'	=>	$this->input->post('fullname'),
						'email'		=>	$this->input->post('email'),
						'user_cat'	=>	$this->input->post('user_cat'),
						'password'	=>	$password,
						// 'is_edit'	=>	$this->input->post('is_edit'),
						// 'is_view'	=>	$this->input->post('is_view'),
						'active'	=>	1,
					);

				$user_id = $this->User_model->insert($user);				

				if($user_id)
				{
					$this->session->set_userdata('user_id', $user_id);
					$this->session->set_userdata('notify', 'Tài khoản '.$user['username'].' khởi tạo thành công. Mật khẩu: <b>'.$tmp_password.'</b>');
				}

				redirect('user/index');
			}
		}
		else
		{
			// since nothing insert, new user form should display.


		}

		redirect('user/index');
	}

	public function edit($user_id = false)
	{
		$data = array();		

		if(empty($user_id))
			redirect('user/index');

		$data['user_id'] = $user_id;

		$this->session->set_userdata('user_id_selected', $data['user_id']);

		// retrieve user
		$data['user']  = $this->User_model->getUser($user_id);

		if(empty($data['user']))
		{
			redirect('user/index');
		}

		$this->template->set('title', 'Chỉnh sửa người dùng');
		$this->template->set('section', 'Chỉnh sửa thông tin người dùng');

		$updateBtn = $this->input->post('updateBtn');

		$this->load->library('form_validation');

		// load all product that designed by user
		$productDesigns = $this->Product_model->loadAllProductDesigned(false, false, $user_id);

		if(!empty($productDesigns))
			$data['productDesigns'] = $productDesigns['data'];

		$cond1 = array('user_id1' => $user_id);
		$user_revenue = $this->User_revenue_model->search($cond1);		

		$user_revenuearr = array();		
		foreach ($user_revenue as $urevenue) 
		{
			$user_revenuearr[$urevenue->product_id] = $urevenue->revenue;
		}

		if(!empty($user_revenuearr))
			$data['user_revenuearr'] = $user_revenuearr;

		if($updateBtn)
		{
			//$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');			
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
			$this->form_validation->set_rules('fullname', 'Fullname', 'trim|required|xss_clean');
			$is_uploadImage = $this->validate_image();

			if ($this->form_validation->run() == FALSE || !$is_uploadImage)
			{
				$data['error'] = validation_errors();				

				$this->template->load('admin/template','admin/edit_user',$data);			
			}
			else
			{				
				$edit = $this->input->post('is_edit');
				$view = $this->input->post('is_view');
				$pass = $this->input->post('pass');
				$fullname = $this->input->post('fullname');
				$view_order = $this->input->post('view_order');
				$website = $this->input->post('website');
				$desc = $this->input->post('desc');

				$data = array(						
						'fullname'		=>	$fullname,
						'website'		=>	$website,
						'desc'			=>	$desc,
						'image'			=>	empty($_FILES['userfile']['name']) ? $data['user']->image : $is_uploadImage,
						'email'			=>	$this->input->post('email'),
						'is_view'		=>	!empty($view) ? $view : 0,
						'is_edit'		=>	!empty($edit) ? $edit : 0,
						'active'		=>	$this->input->post('active'),
						'view_order'	=>	$view_order,
					);

				// resize image 182x250
				if(!empty($_FILES['userfile']['name']))
				{
					$this->resize_image($is_uploadImage, 182, 250);					
				}

				if(!empty($pass))
				{
					$data['password'] = md5($pass);					
				}

				$this->User_model->update($data,$user_id);				

				if(!empty($pass))
				{
					$this->session->set_userdata('notify', 'Tài khoản '.$username.' cập nhật thành công. Mật khẩu: <b>'.$pass.'</b>');
				}

				redirect('user/index');
			}
		}
		else
		{
			$this->template->load('admin/template','admin/edit_user',$data);
		}
	}

	/////////////// this function is specially for admin ///////////////////
	public function changeAdminPass()
	{
		$this->template->set('title', 'Đổi mật khẩu admin');
		$this->template->set('section', 'Đổi thông tin mật khẩu admin');

		$notify = $this->session->userdata('notify');

		if(!empty($notify))
			$data['notify'] = $notify;

		$changePassBtn = $this->input->post('changePassBtn');

		// looking for admin account
		$admin = $this->User_model->retrieveUser('admin'); //fixed

		$admin_id = '';
		if(empty($admin))
		{
			redirect($_SERVER['HTTP_REFERER']);
		}	
		
		$admin_id = $admin->id;	
		$data['admin'] = $admin;

		if($changePassBtn)
		{
			$this->load->library('form_validation');

			$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');		

			if ($this->form_validation->run() == FALSE)
			{
				$data['error'] = validation_errors();				

				$this->template->load('admin/template','admin/changeAdminPass',$data);			
			}
			else
			{				
				// retrieve pass and update
				$data = array('password' => $this->input->post('password'));

				$password_change = $data['password'];
				$data['password'] = md5($data['password']);

				$this->User_model->update($data, $admin_id);

				// pop up new pass and asking for re-login	
				$data['notify'] = 'Mật khẩu thay đổi thành công ! Mật khẩu mới <b>'.$password_change.'</b>. Vui lòng thoát tài khoản để đăng nhập lại';

				$this->template->load('admin/template','admin/changeAdminPass',$data);
			}
		}
		else
		{
			// load change pass form
			$this->template->load('admin/template','admin/changeAdminPass',$data);
		}
	}

	public function autocomplete() 
	{
        $search_data = $this->input->post('search_data');
        $query = $this->User_model->getUserInfo($search_data);

        echo '<select class="form-control" name="user_id">';
        foreach ($query->result() as $row):
            echo "<option value='".$row->id."'>" . $row->fullname . "</option>";
        endforeach;
        echo '</select>';
    }

    // Update revenue
    public function updateRevenue($product_id = false)
    {
    	$revenue = $this->input->post('revenue_'.$product_id);

    	$user_id = $this->session->userdata('user_id_selected');

    	if(empty($user_id))
    		redirect('user');

    	// find record with user_id and product_id
    	$cond = array('product_id' => $product_id,'user_id' => $user_id);

    	$user_revenue = $this->User_revenue_model->search($cond);

    	if(!empty($user_revenue))
    	{
    		$data = array('revenue' => $revenue);

    		$this->User_revenue_model->update($data,$user_revenue->id);
    	}
    	else
    	{
    		$product = $this->Product_model->getEntry($product_id);

    		$data = array(
    				'product_id'	=>	$product_id,    				
    				'user_id'		=>	$user_id,
    				'product_code'	=>	$product->code,
    				'revenue'		=>	$revenue,
    			);

    		$this->User_revenue_model->insert($data);
    	}

    	redirect('user/edit/'.$user_id);
    }


    //////////////////////////////////////////////////////////////

	public function validate_image()
	{
	    $config['upload_path'] = './uploads/image/designer/';
	    $config['allowed_types'] = 'gif|jpg|png|jpg|jpeg';
	    $config['max_size']    = '10000';
	    $config['max_width']  = '10240';
	    $config['max_height']  = '7680';

	    $this->upload->initialize($config);

	    // if empty image upload then return true, since nothing to update
	    $image_upload = $_FILES['userfile']['name'];

	    if(empty($image_upload))
	    	return true;
	    
	    if (!$this->upload->do_upload('userfile'))
	    {
	        $this->session->set_userdata('error_upload', $this->upload->display_errors());	        

	        return false;
	    } else {
	    	$data = array('upload_data' => $this->upload->data());
	    	
	        return $data['upload_data']['file_name'];
	    }
	}	

	// resize image
	public function resize_image($uploaded_image,$width,$height)
	{
		$this->load->library('image_lib');

		$config['image_library'] = 'gd2';
		$config['source_image']	= './uploads/image/designer/'.$uploaded_image;
		$config['create_thumb'] = false;
		$config['maintain_ratio'] = false;
		$config['width']	 = $width;
		$config['height']	= $height;

		$this->image_lib->clear();
	    $this->image_lib->initialize($config);
	    $this->image_lib->resize();
	}
}